package cn.tedu.atomic;

public class VolatileDemo2 {
    static volatile int i = 0;

    public static void main(String[] args) throws InterruptedException {
        Data data = new Data();
        new Thread(new Sum(data)).start();
        new Thread(new Sum(data)).start();

        Thread.sleep(3000);
        // 如果volatile保证原子性(保证线程安全), 那么累加的结果应该是20000, 但是结果不一定是20000, 所以volatile不保证原子性
        System.out.println(data.i);
    }
}

class Sum implements Runnable {
    private Data data;

    public Sum(Data data) {
        this.data = data;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10000; ++i) {
            data.i++;
        }
    }
}
